<?php

// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

function dd($data)
{
    echo '<pre/>';
    print_r($data);
    exit;
}

function dp($data)
{
    echo '<pre/>';
    print_r($data);
}
/**
 * 判断当前登录的是否是超级管理员.
 *
 * @return bool
 */
function is_education_admin()
{
    $user = session('user');
    if ($user && 1 === $user['group_id']) {
        return $user ? true : false;
    }
}

/**
 * 获取当前登录用户的角色id(group_id).
 *
 * @return int
 */
function get_current_group_id()
{
    return session('user')['group_id'];
}

/**
 * 获取当前登录用户的所属集团id(company_id).
 *
 * @return bool
 */
function get_current_company_id()
{
	return session('user')['company_id'];
}

/**
 * 获取当前登录用户的所属区域id(regional_id).
 *
 * @return bool
 */
function get_current_regional_id()
{
	return session('user')['regional_id'];
}

/**
 * 获取当前登录用户的所属校区id(campus_id).
 *
 * @return bool
 */
function get_current_campus_id()
{
    return session('user')['campus_id'];
}

/**
 * 获取当前登录用户的所属校区(campus_name).
 *
 * @return bool
 */
function get_current_campus_name()
{
    return session('user')['campus_name'];
}

/**
 * 获取当前登录用户.
 *
 * @return bool
 */
function get_current_name()
{
    return session('user')['name'];
}

/**
 * 获取当前登录用户ID.
 *
 * @return bool
 */
function get_current_id()
{
    return session('user')['id'];
}

/**
 * 获取当前登录用户头像.
 *
 * @return bool
 */
function get_current_avatar()
{
    return session('user')['img'];
}

/**
 * 获取当前登录用户权限类型.
 *
 * @return bool
 */
function get_current_type()
{
	return session('user')['wtype'];
}

/**
 * 获取当前登录用户属性类型.
 * 1:其他，2:老师类，3:助教类，4:班主任类，5:教务类
 * @return bool
 */
function get_current_group_type()
{
    return session('user')['group_type'];
}

// 应用公共文件
/**
 * 获取客户端IP地址
 *
 * @param int  $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param bool $adv  是否进行高级模式获取（有可能被伪装）
 *
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    //static $ip  =   NULL;
    // if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr, true);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
        if ('127.0.0.1' === $ip) {
            $ip = get_client_ip(0, true);
        }
    }
    // IP地址合法验证
    $long = sprintf('%u', ip2long($ip));
    $ip = $long ? [$ip, $long] : ['0.0.0.0', 0];

    return $ip[$type];
}

/**
 * 递归菜单.
 *
 * @param $array
 * @param int $type  1:顺序菜单 2:树状菜单
 * @param int $fid
 * @param int $level
 *
 * @return array
 */
function get_column($array, $type = 1, $fid = 0, $level = 0)
{
    $column = [];
    if (2 === $type) {
        foreach ($array as $key => $vo) {
            if ($vo['pid'] === $fid) {
                $vo['level'] = $level;
                $column[$key] = $vo;
                $column[$key][$vo['id']] = get_column($array, $type = 2, $vo['id'], $level + 1);
            }
        }
    } else {
        foreach ($array as $key => $vo) {
            if ($vo['pid'] === $fid) {
                $vo['level'] = $level;
                $column[] = $vo;
                $column = array_merge($column, get_column($array, $type = 1, $vo['id'], $level + 1));
            }
        }
    }

    return $column;
}

/**
 * 读取文件
 * @param $filename
 * @return array
 */
function readExcelFile($filename)
{
    /*格式

    'Xlsx' => Reader\Xlsx::class,
    'Xls' => Reader\Xls::class,
    'Xml' => Reader\Xml::class,
    'Ods' => Reader\Ods::class,
    'Slk' => Reader\Slk::class,
    'Gnumeric' => Reader\Gnumeric::class,
    'Html' => Reader\Html::class,
    'Csv' => Reader\Csv::class,

     */
    $readtype = ucfirst(explode('.', $filename)[1]);
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($readtype);
    $spreadsheet = $reader->load($filename); //载入excel表格
    $worksheet = $spreadsheet->getActiveSheet();
    $highestRow = $worksheet->getHighestRow('A'); // 总行数
    $highestColumn = $worksheet->getHighestColumn(1); // 总列数
    $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
    $excelData = [];
    for ($row = 2; $row <= $highestRow; ++$row) {  //控制行数
        for ($col = 1; $col < $highestColumnIndex; ++$col) {  //控制列数
            $excelData[$row][] = (string) $worksheet->getCellByColumnAndRow($col, $row)->getValue();
        }
    }

    return $excelData;
}

/**
 * 生成64位商户订单号
 * @return string
 */
function generateOrdNo()
{
	$number = '';
	$year = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
	$number .= 'SXFZS'.$year[intval(date('Y')) - 2019] . date('mdHis').substr(microtime(), 2, 3) . sprintf('%02d', rand(00, 99));
	return $number;
}

function fileUpload($file, $path, $saveName = false){            //函数会默认将同名文件覆盖
	if($file['file']['error']){                                    //返回代码不为0是表示上传失败，为0则为成功
		$msg['code'] = 0;
		$msg['msg'] = '上传失败！';
	}else{
		if($saveName == false){                                    //如果保存文件名为空，则将上传的文件移动到相应目录
			move_uploaded_file($file['file']['tmp_name'], $path.$file['file']['name']);
		}else{
			$arr = explode(".", $file['file']['name']);            //如果保存文件名不为空，则将上传的文件移动到相应目录，并按指定文件名命名
			move_uploaded_file($file['file']['tmp_name'], $path.$saveName.".".end($arr));
		}
		$msg['code'] = 1;
		$msg['msg'] = '上传成功！';
	}
	return $msg;
}

/**
 * 清除TP的文件缓存
 * User: wufeng
 * Date: 2019/6/4
 *
 * @param $dir
 */
function deldir($dir) {
	$dh = opendir($dir);
	while ($file = readdir($dh)) {
		if ($file != "." && $file != "..") {
			$fullpath = $dir . "/" . $file;
			if (!is_dir($fullpath)) {
				unlink($fullpath);
			} else {
				deldir($fullpath);
			}
		}
	}
}

/**
 * 转换成格式化时间 如 2017-11-11 11:11:11.
 *
 * @param null $time
 *
 * @return false|string
 */
function datetime($time = null)
{
	return $time ? date('Y-m-d H:i:s', $time) : date('Y-m-d H:i:s', time());
}

/**
 * curl get方式
 * User: Truman
 * Date: 2020/08/12
 *
 * @param $url
 * @return bool|string
 */
function curl_get($url)
{
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$data = curl_exec($curl);
	curl_close($curl);

	return $data;
}

/**
 * curl post方式
 * User: Truman
 * Date: 2020/08/12
 *
 * @param $url
 * @param $param
 * @return bool|string
 */
function curl_post($url, $param)
{
	$param = json_encode($param, JSON_UNESCAPED_UNICODE);
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

	return curl_exec($ch);
}

/**
 * 判断是否json.
 *
 * @param $str
 *
 * @return bool
 */
function isjson($str)
{
	return null === json_decode($str) ? false : true;
}

/**
 * 获取系统设置.
 *
 * @param string $key
 *
 * @return mixed|string
 */
function getSetting($key = '')
{
	$systemSettingModel = new \app\models\SettingModel();

	return $systemSettingModel->getValue($key);
}

/**
 * 获取多个系统设置.
 *
 * @param string $key //多个英文逗号分隔
 *
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 *
 * @return array
 */
function getMultipleSetting($key = '')
{
	$systemSettingModel = new \app\models\SettingModel();

	return $systemSettingModel->getMultipleValue($key);
}

/**
 * @param $code
 * @param bool $mini
 *
 * @return array|mixed
 */
function error_code($code, $mini = false)
{
	$result = [
		'status' => false,
		'data' => $code,
		'msg' => config('error.10000'),
	];

	$result['msg'] = config('error.'.$code);
	if ($mini) {
		return $result['msg'];
	}

	return $result;
}

/**
 * 判断是否手机号.
 *
 * @param $mobile
 *
 * @return bool
 */
function isMobile($mobile = '')
{
	if (preg_match('/^1[3456789]{1}\\d{9}$/', $mobile)) {
		return true;
	}

	return false;
}